//var WxParse = require('../../lib/wxParse/wxParse.js');
const App = getApp();

import {
  GoodsDetailModel
} from '../../models/goodsdetail.js';

import {
  CartModel
} from '../../models/cart.js';

import {
  UserModel
} from '../../models/user.js';

const goodsDetailModel = new GoodsDetailModel();
const cartModel = new CartModel();
const userModel = new UserModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    gallery: [],
    goodsInfo: {},
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '请选择规格数量',
    openAttr: false,
    noCollectImage: "/images/icon_collect.png",
    hasCollectImage: "/images/icon_collect_checked.png",
    collectBackImage: "/images/icon_collect.png"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: parseInt(options.id)
      });
    }

    this.getGoodsDetailData();
  },

  // 加载购物车数量
  getCartGoodsCount: function() {
    cartModel.getCartGoodsCount().then(res => {
      if (res.errno === 0) {
        this.setData({
          cartGoodsCount: res.data.cartTotal.goodsCount
        })
      }
    })
  },

  // 加载商品详情页数据
  getGoodsDetailData: function() {
    wx.showLoading({
      title: '加载中...',
    });

    goodsDetailModel.getGoodsDetail(this.data.id).then(res => {
      if (res.errno === 0) {
        this.setData({
          gallery: res.data.gallery,
          goodsInfo: res.data.info,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          comment: res.data.comment,
          brand: res.data.brand,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect
        });

        if (res.data.userHasCollect == 1) {
          this.setData({
            collectBackImage: this.data.hasCollectImage
          });
        } else {
          this.setData({
            collectBackImage: this.data.noCollectImage
          });
        }

        // WxParse.wxParse('goodsDetail', 'html', res.data.info.goods_desc, this);

        this.getGoodsRelatedData();

        this.getCartGoodsCount();

        this.setSpecValueStatus();
      }

      wx.hideLoading()
    })
  },

  // 加载相关商品数据
  getGoodsRelatedData: function() {
    goodsDetailModel.getGoodsRelated(this.data.id).then(res => {
      // console.log(res);
      if (res.errno === 0) {
        this.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    })
  },

  // 打开规格数量层
  onSwitchAttrPop: function() {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      })
    }
  },

  // 关闭规格数量层
  onCloseAttr: function() {
    this.setData({
      openAttr: false
    })
  },

  // 点击加入购物车事件
  onAddToCart: function() {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      })
    }
    else {
      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
        wx.showToast({
          image: '/images/icon_error.png',
          title: '请选择规格',
          mask: true
        });
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());

      if (!checkedProduct || checkedProduct.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/images/icon_error.png',
          title: '库存不足',
          mask: true
        });
        return false;
      }

      //验证库存
      if (checkedProduct[0].goods_number < this.data.number) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/images/icon_error.png',
          title: '库存不足',
          mask: true
        });
        return false;
      }

      let p_goodsId = this.data.goodsInfo.id;
      let p_number = this.data.number;
      let p_productId = checkedProduct[0].id;
      
      cartModel.getCartAdd(p_goodsId, p_number, p_productId).then(res => {
        console.log(res);
        if (res.errno == 0) {
          wx.showToast({
            title: '添加购物车成功'
          });
          this.setData({
            openAttr: !this.data.openAttr,
            cartGoodsCount: res.data.cartTotal.goodsCount
          });
        } else {
          wx.showToast({
            image: '/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      })
    }
  },

  validation: function() {
  },

  // 设置颜色/规格的第一个默认选中状态
  setSpecValueStatus: function () {
    let _specList = this.data.specificationList;
    for (let i = 0; i < _specList.length; i++) {
      _specList[i].valueList[0].checked = true;
    }

    this.setData({
      specificationList: _specList
    });
  },
  
  // 选择颜色/规格
  onClickSkuValue: function(event) {
    let specNameId = event.currentTarget.dataset.nameId;
    let specValueId = event.currentTarget.dataset.valueId;

    // 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specList = this.data.specificationList;
    for (let i = 0; i < _specList.length; i++) {
      if (_specList[i].specification_id == specNameId) {
        for (let j = 0; j < _specList[i].valueList.length; j++) {
          if (_specList[i].valueList[j].id == specValueId) {
            // 如果已经选中，则取消选中
            if (_specList[i].valueList[j].checked) {
              _specList[i].valueList[j].checked = false;
            }
            else {
              _specList[i].valueList[j].checked = true;
            }
          }
          else {
            _specList[i].valueList[j].checked = false;
          }
        }
      }
    }

    this.setData({
      specificationList: _specList
    });
    
    this.changeSpecInfo();
  },

  // 判断颜色/规格是否选择完整
  isCheckedAllSpec: function () {
    return this.getCheckedSpecValue().every(function (v) {
      if (v.valueId != 0) {
        return true;
      }
    });
  
    // 用some的写法
    // return !this.getCheckedSpecValue().some(function (v) {
    //   if (v.valueId == 0) {
    //     return true;
    //   }
    // });
  },

  // 获取选中颜色/规格的值Id
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });

    return checkedValue.join('_');
  },

  // 获取选中的颜色/规格信息
  getCheckedSpecValue: function() {
    let checkedValues = [];
    let _specList = this.data.specificationList;
    for (let i = 0; i< _specList.length; i++) {
      let _checkedObj = {
        nameId: _specList[i].specification_id,
        valueId: 0,
        valueText: ''
      };
      for (let j = 0; j < _specList[i].valueList.length; j++) {
        if (_specList[i].valueList[j].checked) {
          _checkedObj.valueId = _specList[i].valueList[j].id;
          _checkedObj.valueText = _specList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }
    
    return checkedValues;
  },

  //设置选择的颜色/规格信息
  changeSpecInfo: function () {
    let checkedNameValue = this.getCheckedSpecValue();

    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        'checkedSpecText': checkedValue.join('　')
      });
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量'
      });
    }
  },
  
  // 判断是否有对应的sku信息
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.goods_specification_ids == key) {
        return true;
      } else {
        return false;
      }
    });
  },

  // 数量 +1
  cutNumber: function() {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    })
  },

  // 数量 -1
  addNumber: function() {
    let stockNum = this.data.goodsInfo.goods_number;
    if (this.data.number + 1 <= stockNum) {
      this.setData({
        number: this.data.number + 1
      })
    }
    else {
      this.setData({
        number: stockNum
      })
      wx.showToast({
        icon: 'none',
        title: '抱歉，库存不足了！'
      });
    }
  },

  // 收藏与取消收藏商品
  addCannelCollect: function(){
    userModel.getCollectAddOrDelete(0, this.data.id).then(res => {
      // console.log(res);
      if (res.errno == 0) {
        if (res.data.type == 'add') {
          this.setData({
            collectBackImage: this.data.hasCollectImage
          });
          wx.showToast({
            title: '收藏成功',
            mask: true
          });
        } else {
          this.setData({
            collectBackImage: this.data.noCollectImage
          });
          wx.showToast({
            title: '取消收藏成功',
            mask: true
          });
        }
      } else {
        wx.showToast({
          image: '/images/icon_error.png',
          title: res.errmsg,
          mask: true
        });
      }
    })
  },
  
  // 点 “购物车图标” 跳转到购物车页面
  openCartPage: function() {
    wx.switchTab({
      url: '/pages/cart/index',
    });
  },

  // 点 “立即购买” 跳转到结算页面
  onBuyNow: function(event) {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      })
    }
    else {
      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
        wx.showToast({
          image: '/images/icon_error.png',
          title: '请选择规格',
          mask: true
        });
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());

      if (!checkedProduct || checkedProduct.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/images/icon_error.png',
          title: '库存不足',
          mask: true
        });
        return false;
      }

      //验证库存
      if (checkedProduct[0].goods_number < this.data.number) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/images/icon_error.png',
          title: '库存不足',
          mask: true
        });
        return false;
      }

      let p_goodsId = this.data.goodsInfo.id;
      let p_number = this.data.number;
      let p_productId = checkedProduct[0].id;
      
      wx.navigateTo({
        url: '/pages/shopping/checkout/index?'+ App.urlEncode({
          order_type: 'buyNow',
          goods_id: p_goodsId,
          number: this.data.number,
          productId: checkedProduct[0].id,
        }),
      });
    }
  }
})